

// promise简易版实现 只实现resolve和reject,then方法

class MyPromise{ //permise本质上就是一个类,使用resolve和reject去改变状态,用then去收集回调
    //构造函数
    constructor(executor){
        this.state = 'pending'; //定义promise的状态
        this.value = undefined; //定义promise的值
        this.reason = undefined; //定义promise的失败原因
        this.onFulfilledCallbacks = []; //定义成功回调,使用数组,可能有多个成功回调,就是对一个promise对象多次调用then方法
        this.onRejectedCallbacks = []; //定义失败回调,使用数组,可能有多个失败回调,就是对一个promise对象多次调用catch方法

        // 使用箭头函数确保this指向正确,定义在构造函数中是为了防止外部调用,只能在new的时候调用
        const resolve = (value) => { //定义resolve函数
            if(this.state === 'pending'){
                this.state = 'fulfilled'; //改变状态
                this.value = value; //改变值,将resolve的参数赋值给value
                this.onFulfilledCallbacks.forEach(callback => callback()); //执行成功回调
            }
        }

        const reject = (reason) => { //定义reject函数
            if(this.state === 'pending'){
                this.state = 'rejected'; //改变状态
                this.reason = reason; //改变失败原因,将reject的参数赋值给reason
                this.onRejectedCallbacks.forEach(callback => callback()); //执行失败回调
            }
        }

        try {
            executor(resolve, reject); //执行传入的函数,executor是传递进来的函数,resolve和reject在传递进来的函数中进行调用    
        } catch (error) {
            reject(error); //如果传入的函数抛出错误,则调用reject函数
        }
    }

    // 将then方法定义在类的原型上,因为then方法是一个实例方法,所以需要定义在原型上
    then(onFulfilled, onRejected) { //定义then函数
        if(this.state === 'fulfilled'){
            onFulfilled(this.value);
        }
        if(this.state === 'rejected'){
            onRejected(this.reason);
        }
        if(this.state === 'pending'){ 
            //如果处于pending状态,则将onFulfilled和onRejected添加到数组中,等resolve或者reject被调用时,再执行回调
            this.onFulfilledCallbacks.push(() => {//包装函数,用于延迟执行,传参,加逻辑等
                //通过闭包使用未来的this.value,到时候执行resolve的时候这个value值是会被改变的
                onFulfilled(this.value); 
            });
            this.onRejectedCallbacks.push(() => {
                onRejected(this.reason);
            });
        }
    }
}

// ========== 测试例子：展示每一段代码的作用 ==========

console.log('=== 测试1：立即成功的Promise ===');
const promise1 = new MyPromise((resolve, reject) => {
    console.log('executor立即执行');
    resolve('立即成功'); // 立即调用resolve
});

console.log('Promise1状态:', promise1.state); // fulfilled,因为传入的代码不是异步代码,所以立即执行
console.log('Promise1值:', promise1.value); // 立即成功

promise1.then(result => {  //此时promise.status为fulfilled,所以会立即执行onFulfilled回调
    console.log('Promise1成功回调:', result);
}, error => {
    console.log('Promise1失败回调:', error);
});

console.log('\n=== 测试2：延迟成功的Promise ===');
const promise2 = new MyPromise((resolve, reject) => {  //这个promise定义完之后状态是pending
    console.log('executor立即执行，但resolve延迟调用');
    setTimeout(() => {
        console.log('1秒后调用resolve');
        resolve('延迟成功');
    }, 1000);
});

console.log('Promise2初始状态:', promise2.state); // pending
console.log('Promise2初始值:', promise2.value); // undefined

// 在resolve调用之前注册回调,会将回调存储到数组当中去
promise2.then(result => {
    console.log('Promise2成功回调:', result);
}, error => {
    console.log('Promise2失败回调:', error);
});

//注意这里输出,有细节在里面的: 1.result这个值需要被resolve之后才有具体的值
console.log("此时存储在promise2中的成功回调数组的函数\n", promise2.onFulfilledCallbacks.toString());




// 1秒后状态会改变   //加入到消息队列,1s之后执行
setTimeout(() => {
    console.log('Promise2最终状态:', promise2.state); // fulfilled
    console.log('Promise2最终值:', promise2.value); // 延迟成功
}, 1500);

console.log('\n=== 测试3：失败的Promise ===');
const promise3 = new MyPromise((resolve, reject) => {
    console.log('executor执行，调用reject');
    reject('操作失败');
});

promise3.then(result => {
    console.log('Promise3成功回调:', result);
}, error => {
    console.log('Promise3失败回调:', error);
});

console.log('\n=== 测试4：多个then回调 ===');
const promise4 = new MyPromise((resolve, reject) => {
    console.log('executor执行，延迟resolve');
    setTimeout(() => {
        resolve('多个回调测试');
    }, 2000); // 改为2秒，让测试2先执行
});

// 注册多个then回调
promise4.then(result => {
    console.log('Promise4回调1:', result);
}, error => {
    console.log('Promise4错误1:', error);
});

promise4.then(result => {
    console.log('Promise4回调2:', result);
}, error => {
    console.log('Promise4错误2:', error);
});

promise4.then(result => {
    console.log('Promise4回调3:', result);
}, error => {
    console.log('Promise4错误3:', error);
});

console.log('\n=== 测试5：executor抛出错误 ===');
const promise5 = new MyPromise((resolve, reject) => {
    console.log('executor执行，抛出错误');
    throw new Error('executor中的错误');
});

promise5.then(result => {
    console.log('Promise5成功回调:', result);
}, error => {
    console.log('Promise5失败回调:', error.message);
});

console.log('\n=== 测试6：状态不可变 ===');
const promise6 = new MyPromise((resolve, reject) => {
    console.log('executor执行');
    resolve('第一次成功');
    resolve('第二次成功'); // 不会生效
    reject('失败'); // 不会生效
});

promise6.then(result => {
    console.log('Promise6成功回调:', result);
}, error => {
    console.log('Promise6失败回调:', error);
});

console.log('\n=== 测试完成 ===');






